<script lang="ts" setup>
//文章中的图像
import { IndexShowData } from "@/api/interface";
import { onMounted, ref, watch, watchEffect } from "vue";
export interface Props {
  data: IndexShowData["image"];
  config: {
    small: string;
    medium: string;
    large: string;
  };
}

//接收数据
const props = defineProps<Props>();
//判断条件
const active = ref(true);

//存储图片信息

const small = ref("");
const medium = ref("");
const large = ref("");

/**
 * 有时一些尺寸可能没有，这里处理下
 * @param data 对象
 * @param size 尺寸
 */

const handleSize = (data: any, size: string) => {
  const targetSizes = {
    thumbnail: ["medium", "medium_large", "large", "ywsl", "full"], //150
    medium: ["medium_large", "large", "ywsl", "full"], //300
    medium_large: ["large", "ywsl", "full"], //768
    large: ["ywsl", "full"], //1024
    ywsl: ["full"], //1536
  };

  if (size === "thumbnail" && !data[size]) {
    return targetSizes.thumbnail.find((s) => data[s]) || size;
  }

  if (size === "medium" && !data[size]) {
    return targetSizes.medium.find((s) => data[s]) || size;
  }

  if (size === "medium_large" && !data[size]) {
    return targetSizes.medium_large.find((s) => data[s]) || size;
  }

  if (size === "large" && !data[size]) {
    return targetSizes.large.find((s) => data[s]) || size;
  }

  if (size === "ywsl" && !data[size]) {
    return targetSizes.ywsl.find((s) => data[s]) || size;
  }

  return size;
};

//有缩略图时取出缩略图中的值
const handleData = (data: any) => {
  //尺寸对照表可见interface.ts文件中的相关定义

  //移动端
  const s = handleSize(data, props.config.small);

  small.value = data[s].source_url;

  //平板端
  const m = handleSize(data, props.config.medium);
  medium.value = data[m].source_url;
  //PC端
  const l = handleSize(data, props.config.large);
  large.value = data[l].source_url;
};

onMounted(() => {
  //两种情况 - 有提供缩略图则使用，不提供则用原图
  const data = props.data.details.sizes;

  if (JSON.stringify(data) !== "{}" && typeof data !== "undefined") {
    //非空，用缩略图

    handleData(data);
  } else {
    //是空的，用原图
    active.value = !active.value;
  }
});
</script>
<template>
  <template v-if="active">
    <picture>
      <source media="(min-width: 734px)" :srcset="small" />
      <source media="(min-width: 1068px)" :srcset="medium" />
      <el-image :src="large" fit="cover" lazy> </el-image>
    </picture>
  </template>
  <template v-else>
    <el-image :src="data.url" fit="cover" lazy> </el-image>
  </template>
</template>
<style lang="less" scoped></style>
